package com.syj.jsxjj.ui.lend.fragment;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.syj.jsxjj.R;
import com.syj.jsxjj.base.BaseFragment;
import com.syj.jsxjj.http.HttpManager;
import com.syj.jsxjj.http.HttpSubscriber;
import com.syj.jsxjj.ui.lend.adapter.LoanFilterListAdapter;
import com.syj.jsxjj.ui.lend.bean.LoanList;
import com.syj.jsxjj.ui.lend.bean.RadioVo;
import com.syj.jsxjj.util.SpUtil;
import com.syj.jsxjj.util.ToastUtil;
import com.syj.jsxjj.widget.CallBack;
import com.syj.jsxjj.widget.DrawableCenterTextView;
import com.syj.jsxjj.widget.recycler.BaseRecyclerAdapter;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


/**
 * 贷款
 */
public class LoanFragment extends BaseFragment {
    public static final String TAG = "LoanFragment";
    //筛选主题
    private static final String[] tabTitle = {"不限金额", "默认类型", "默认排序"};
    //贷款金额
    private static final String[] loanAmount = {"不限金额", "2千以下", "2千~5千", "5千~1万", "1万以上"};
    //排序方式
    private static final String[] loanSort = {"默认排序", "利率", "额度"};
    @BindView(R.id.tv_left)
    DrawableCenterTextView mTvLeft;
    @BindView(R.id.tv_close)
    DrawableCenterTextView mTvClose;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_right)
    DrawableCenterTextView mTvRight;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_recommend)
    TextView mTvRecommend;
    @BindView(R.id.fl_loan_list)
    FrameLayout mFlLoanList;
    @BindView(R.id.dropDownMenu)
    com.syj.jsxjj.widget.DropDownMenu mDropDownMenu;
    @BindView(R.id.tab_bg_1)
    FrameLayout mTabBg1;
    @BindView(R.id.tab_bg_2)
    FrameLayout mTabBg2;
    @BindView(R.id.tab_bg_3)
    FrameLayout mTabBg3;

    private ArrayList<RadioVo> amounts;
    private ArrayList<RadioVo> conditions;
    private ArrayList<RadioVo> sorts;

    private LoanListFragment mListFragment;
    private List<LoanList.ProductTypeList> productTypeList;
    private int numPerPage = 15, pageNum = 1;
    private List<View> popupViews = new ArrayList<>();

    private LoanFilterListAdapter conditionsAdapter;
    private boolean hasRequestProductType; //是否请求过

    @Override
    public int getLayoutId() {
        return R.layout.fragment_loan;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void loadData() {
        //学生1 上班2  其他4
        mTitle.setTitle("更多借款产品");
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(SpUtil.getString("moneyList"))) {
            bundle.putString("checkMoney", SpUtil.getString("moneyList"));
            mListFragment = LoanListFragment.getInstance(bundle);
        } else {
            mListFragment = LoanListFragment.getInstance(null);
        }
        getChildFragmentManager().beginTransaction()
                .replace(R.id.fl_loan_list, mListFragment).commit();

        initMenuData();
    }


    private String indexMoneyType, productType, sort;

    private void initMenuData() {
        indexMoneyType = "";
        productType = "";
        sort = "";

        amounts = new ArrayList<>();
        for (String s : loanAmount) {
            if (TextUtils.equals("不限金额", s)) {
                amounts.add(new RadioVo(s, true));
            } else {
                amounts.add(new RadioVo(s, false));
            }
        }

        conditions = new ArrayList<>();
        conditions.add(new RadioVo("默认类型", true));

        sorts = new ArrayList<>();
        for (String s : loanSort) {
            if (TextUtils.equals("默认排序", s)) {
                sorts.add(new RadioVo(s, true));
            } else {
                sorts.add(new RadioVo(s, false));
            }
        }
        conditionsAdapter = new LoanFilterListAdapter();
        requestConditions();
        initMenu();
    }

    private void requestConditions() {
        if (hasRequestProductType) return;

        final Map<String, String> map = new HashMap<>();
        map.put("numPerPage", numPerPage + "");
        map.put("pageNum", pageNum + "");
        map.put("appType", "1");

        toSubscribe(HttpManager.getApi().findProductInfoList(map), new HttpSubscriber<LoanList>() {
            @Override
            protected void _onStart() {

            }

            @Override
            protected void _onNext(final LoanList result) {
                hasRequestProductType = true;

                productTypeList = result.getProductTypeList();
                for (LoanList.ProductTypeList vo : productTypeList) {
                    conditions.add(new RadioVo(vo.getTypeName(), false));
                }
                conditionsAdapter.clearData();
                conditionsAdapter.addData(conditions);
            }

            @Override
            protected void _onError(String message) {
                ToastUtil.showToast(message);
            }

            @Override
            protected void _onCompleted() {

            }
        });
    }

    /**
     * 重置下拉列表所有数据的选中状态为false
     *
     * @param list
     */
    private void resetList(List<RadioVo> list) {
        for (RadioVo vo : list) {
            vo.setFlag(false);
        }
    }

    /**
     * dropdownmenu
     */
    private void initMenu() {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        /*贷款金额*/
        RecyclerView rvAmount = new RecyclerView(mActivity);
        rvAmount.setOverScrollMode(View.OVER_SCROLL_NEVER);
        rvAmount.setLayoutParams(params);
        rvAmount.setLayoutManager(new LinearLayoutManager(mActivity));

        final LoanFilterListAdapter amountAdapter = new LoanFilterListAdapter();
        rvAmount.setAdapter(amountAdapter);
        amountAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                String tempType = indexMoneyType;

                switch (position) {
                    case 0:
                        indexMoneyType = "";
                        break;
                    case 1:
                        indexMoneyType = "one";
                        break;
                    case 2:
                        indexMoneyType = "two";
                        break;
                    case 3:
                        indexMoneyType = "three";
                        break;
                    case 4:
                        indexMoneyType = "four";
                        break;
                }

                if (!TextUtils.equals(tempType, indexMoneyType)) {
                    Map<String, String> map_ekv = new HashMap<String, String>();
                    map_ekv.put("LoanMoney", indexMoneyType);

                    updatePullDownMenu(position, amountAdapter, loanAmount[position], amounts);
                    updateLoanList();
                }
            }
        });
        amountAdapter.addData(amounts);

        /*贷款条件*/
        RecyclerView rvConditions = new RecyclerView(mActivity);
        rvConditions.setOverScrollMode(View.OVER_SCROLL_NEVER);
        rvConditions.setLayoutParams(params);
        rvConditions.setLayoutManager(new LinearLayoutManager(mActivity));

//        conditionsAdapter = new LoanFilterListAdapter();
        rvConditions.setAdapter(conditionsAdapter);
        conditionsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                String tempType = productType;
                productType = position == 0 ? "" : productTypeList.get(position - 1).getLinkUrl();
                if (!TextUtils.equals(tempType, productType)) {
                    Map<String, String> map_ekv = new HashMap<String, String>();
                    map_ekv.put("LoanType", productType);

                    updatePullDownMenu(position, conditionsAdapter, conditions.get(position).getContent(), conditions);
                    updateLoanList();
                }
            }
        });
        conditionsAdapter.addData(conditions);
        /*排序方式*/
        RecyclerView rvSort = new RecyclerView(mActivity);
        rvSort.setOverScrollMode(View.OVER_SCROLL_NEVER);
        rvSort.setLayoutParams(params);
        rvSort.setLayoutManager(new LinearLayoutManager(mActivity));

        final LoanFilterListAdapter sortAdapter = new LoanFilterListAdapter();
        rvSort.setAdapter(sortAdapter);
        sortAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                String tempSort = sort;
                if (position == 0) {
                    sort = "";
                } else if (position == 1) {
                    sort = "1";
                } else if (position == 2) {
                    sort = "2";
                }
                if (!TextUtils.equals(tempSort, sort)) {
                    Map<String, String> map_ekv = new HashMap<String, String>();
                    map_ekv.put("LoanSort", sort);

                    updatePullDownMenu(position, sortAdapter, loanSort[position], sorts);
                    updateLoanList();
                }
            }
        });
        sortAdapter.addData(sorts);

        popupViews.add(rvAmount);
        popupViews.add(rvConditions);
        popupViews.add(rvSort);

        TextView contentView = new TextView(mActivity);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        contentView.setText("");
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

        //init dropdownview
        mDropDownMenu.setDropDownMenu(Arrays.asList(tabTitle), popupViews, contentView, new CallBack() {
            @Override
            public void closeMenu(int position) {
                switch (position) {
                    case 0:
                        mTabBg1.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        mTabBg2.setVisibility(View.INVISIBLE);
                        break;
                    case 2:
                        mTabBg3.setVisibility(View.INVISIBLE);
                        break;
                }
            }

            @Override
            public void openMenu(int position) {
                switch (position) {
                    case 0:
                        mTabBg1.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        requestConditions();
                        mTabBg2.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        mTabBg3.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
    }

    private void updateLoanList() {
        Bundle bundle = new Bundle();
        bundle.putString("indexMoneyType", indexMoneyType);
        bundle.putString("productType", productType);
        bundle.putString("sort", sort);
        mListFragment = LoanListFragment.getInstance(bundle);
        getChildFragmentManager().beginTransaction()
                .replace(R.id.fl_loan_list, mListFragment).commit();
    }

    /**
     * 更新下拉列表的选中状态
     *
     * @param position
     * @param adapter
     * @param text
     * @param data
     */
    private void updatePullDownMenu(int position, LoanFilterListAdapter adapter, String text, ArrayList<RadioVo> data) {
        mDropDownMenu.setTabText(text);
        mDropDownMenu.closeMenu();
        resetList(data);
        data.get(position).setFlag(true);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("贷款"); //统计页面，"MainScreen"为页面名称，可自定义
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mDropDownMenu.closeMenu();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("贷款");
    }

}
